package com.kpa.demo.data.http

import android.content.Context
import com.sf.innovate.hammer.game.ContextHolder
import com.sf.innovate.hammer.game.net.http.interceptor.ErrorHandleInterceptor
import okhttp3.Dispatcher
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.util.concurrent.TimeUnit

object ServiceCreator {
    open var ipstr= "192.168.43.159"
    private val okHttpClient by lazy { OkHttpClient().newBuilder() }
    private val retrofit: Retrofit by lazy {
       // try {
            var host = ContextHolder.instance.mContext.getSharedPreferences("config",Context.MODE_PRIVATE).getString("host",ipstr)
            var hostStr = "http://" + host + "/"
            val builder = Retrofit.Builder()
                .baseUrl(hostStr)
            // .addConverterFactory(GsonConverterFactory.create())
            .addConverterFactory(ScalarsConverterFactory.create())
            val dispatcher = Dispatcher()
            dispatcher.maxRequests = 1
            val httpLoggingInterceptor = HttpLoggingInterceptor()
            httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
            okHttpClient
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
              .addInterceptor(ErrorHandleInterceptor())
                .addInterceptor(httpLoggingInterceptor)
                .addInterceptor(com.kpa.demo.data.http.interceptor.HttpLoggingInterceptor())
                .dispatcher(dispatcher)
            builder.client(okHttpClient.build()).build()
//        }catch (err:Exception){
//            Log.e("cxcx", ": ", err)
//        }

    }

    fun <T> create(clazz: Class<T>): T = retrofit.create(clazz)

    inline fun <reified T> createService(clazz: Class<T>): T =
        create(clazz)

}